<template>
  <div>
    <div class="search">
      <el-input placeholder="请输入名称查询" style="width: 200px"></el-input>
      <el-button type="info" plain style="margin-left: 10px">查询</el-button>
      <el-button type="warning" plain style="margin-left: 10px">重置</el-button>
    </div>

    <div class="operation">
      <el-button type="danger" plain>批量删除</el-button>
    </div>

    <div>
      <el-table
        :data="tabledata"
        style="width: 100%"
        strip
        v-loading="tableloading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          fixed
          width="30"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="id"
          label="id"
          width="50"
          align="center"
        ></el-table-column>

        <el-table-column
          prop="user.name"
          label="用户"
          align="center"
          width="70"
        >
        </el-table-column>

        <el-table-column
          prop="fuwudate"
          label="下单时间"
          align="center"
          width="150"
        >
        </el-table-column>

        <el-table-column
          prop="fuwudate"
          label="服务时间"
          align="center"
          width="150"
        >
          <template v-slot="scope">
            {{ scope.row.fuwudate.slice(0, 16) }}
          </template>
        </el-table-column>

        <el-table-column
          prop="type.fuwurenshu"
          label="服务人数"
          align="center"
          width="100"
        >
          <template v-slot="scope">
            {{ scope.row.json.fuwurenshu }} 人
          </template>
        </el-table-column>

        <el-table-column
          prop="phone"
          label="联系方式"
          align="center"
          width="150"
        ></el-table-column>

        <el-table-column prop="jiner" label="金额：" align="center" width="100">
        </el-table-column>

        <el-table-column prop="paymentStatus" label="订单状态" align="center">
          <template v-slot="scope">
            <el-tag :type="getTabType(scope.row.paymentStatus).type">
              {{ getTabType(scope.row.paymentStatus).text }}</el-tag
            >
          </template>
        </el-table-column>

        <el-table-column
          prop="userdel"
          label="预约状态"
          align="center"
          width="100"
        >
          <template v-slot="scope">
            <el-tag :type="scope.row.userdel === 0 ? 'success' : 'danger'">
              {{ scope.row.userdel === 0 ? "未取消" : "用户以取消" }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="dizhi"
          label="服务地址"
          show-overflow-tooltip
          align="center"
          width="100"
        ></el-table-column>

        <el-table-column
          prop="type.guige"
          label="服务时间（规格）"
          align="center"
          width="150"
        >
          <template v-slot="scope"> {{ scope.row.json.guige }} 小时 </template>
        </el-table-column>

        <el-table-column
          prop="leavingAMessage"
          label="留言"
          align="center"
          width="70"
          show-overflow-tooltip
        >
        </el-table-column>

        <el-table-column label="操作" align="center" width="280" fixed="right">
          <template v-slot="scope">
            <el-button
              size="mini"
              type="primary"
              plain
              @click="bandupdatepaymentStatus(scope)"
              >修改订单状态</el-button
            >
            <el-button
              size="mini"
              type="primary"
              plain
              @click="updateItem(scope)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              plain
              @click="deleteItem(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- <div class="pagination">
        <el-pagination
          background
          @current-change="handleCurrentChange"
          :current-page="pagination.pageNum"
          :page-sizes="[5, 10, 20]"
          :page-size="pagination.pageSize"
          layout="total, prev, pager, next"
          :total="pagination.total"
        >
        </el-pagination>
      </div> -->
    </div>

    <el-dialog
      title="修改订单支付状态"
      :visible.sync="fromVisible"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form label-width="80px" label-position="top">
        <el-form-item label="订单状态：">
          <el-radio-group v-model="form.radio">
            <el-radio label="0" border>已支付</el-radio>
            <el-radio label="1" border>未支付</el-radio>
            <el-radio label="3" border>已完成</el-radio>
            <el-radio label="4" border>待服务</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-button
          type="primary"
          @click="updatepaymentStatus"
          :loading="butloading"
          class="w-full"
          >确定</el-button
        >
      </el-form>
    </el-dialog>

    <el-dialog title="编辑" :visible.sync="fromVisible2">
      <el-form
        label-width="80px"
        label-position="left"
        :rules="rules2"
        :model="form2"
        ref="formRef2"
      >
        <el-form-item label="金额：" prop="jiner">
          <el-input v-model="form2.jiner" clearable />
        </el-form-item>

        <el-form-item label="地址：" prop="dizhi">
          <el-input
            placeholder="请输入地址"
            v-model="form2.dizhi"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="服务人数：" prop="fuwurenshu" label-width="100">
          <el-input-number
            :min="1"
            style="width: 300px"
            v-model="form2.fuwurenshu"
            clearable
          ></el-input-number>
        </el-form-item>
        <el-form-item label="规格：" prop="guige">
          <el-input
            placeholder="请输入规格"
            style="width: 300px"
            v-model="form2.guige"
            type="number"
            clearable
            ><template slot="append">小时</template>
          </el-input>
        </el-form-item>
        <el-form-item label="服务时间：" prop="datetime" label-width="100">
          <el-date-picker
            v-model="form2.datetime"
            type="datetime"
            style="width: 400px"
            clearable
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="手机\电话：" prop="phone" label-width="100">
          <el-input
            placeholder="请输入手机或电话"
            v-model="form2.phone"
            clearable
            class="w-500"
          ></el-input>
        </el-form-item>
        <br />
        <el-form-item label="留言：" prop="leavingAMessage">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 8 }"
            placeholder="留言内容"
            v-model="form2.leavingAMessage"
            style="width: 500px"
            clearable
          >
          </el-input>
        </el-form-item>

        <el-button
          type="primary"
          @click="updateItemSubmit"
          :loading="butloading2"
          class="w-full"
          >确定</el-button
        >
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { cloneDeep } from "lodash-es";
import dayjs from "dayjs";
export default {
  data() {
    var validateMobile = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入手机号"));
      } else if (!/^1[3|5|7|8|9]\d{9}$/.test(value)) {
        callback(new Error("请输入正确的手机号码格式"));
      } else {
        callback();
      }
    };
    return {
      user: JSON.parse(localStorage.getItem("xm-user") || "{}"),
      tableloading: false,
      tabledata: [],
      pagination: {
        pageNum: 1, // 当前的页码
        pageSize: 10, // 每页显示的个数
        total: 0,
      },
      ids: [],
      fromVisible: false,
      form: {
        id: 0,
        radio: "1",
        index: 0,
      },
      butloading: false,
      // 编辑
      fromVisible2: false,
      form2: {
        dizhi: "",
        fuwurenshu: 1,
        guige: 1,
        phone: "",
        datetime: "",
        leavingAMessage: "",
        jiner: "",
      },
      rules2: {
        dizhi: [{ required: true, message: "请输入地址", trigger: "blur" }],
        jiner: [{ required: true, message: "请输入地址", trigger: "blur" }],
        guige: [{ required: true, message: "请输入规格", trigger: "blur" }],
        datetime: [
          { required: true, message: "请选择服务时间", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: validateMobile, trigger: "blur" },
        ],
      },
      butloading2: false,
    };
  },
  created() {
    this.init();
  },
  methods: {
    toogletableloading() {
      this.tableloading = !this.tableloading;
    },
    async init() {
      try {
        this.toogletableloading();
        const res = await this.$request.get("/order/getlist");
        const userRes = await this.$request.get("/user/selectAll");
        if (res.code != 200) {
          this.$message.error(res.msg);
          return;
        }

        this.tabledata = res.data.filter((fv) => {
          if (fv.type == "1") {
            fv.json = JSON.parse(fv.json);
            fv.tag = {
              type: fv.paymentStatus == 1 ? "success" : "info",
              text: fv.paymentStatus == 1 ? "已支付" : "未支付",
            };
            fv.user = userRes.data.find((findv) => findv.id == fv.userId);
            return fv;
          }
        });
      } catch (error) {
        console.log(error);
        this.$message.error("数据加载失败");
      } finally {
        this.toogletableloading();
      }
    },
    handleCurrentChange(pageNum) {
      this.init(pageNum);
    },
    handleSelectionChange(rows) {
      // 当前选中的所有的行数据
      this.ids = rows.map((v) => v.id); //  [1,2]
    },

    getTabType(paymentStatus = 2) {
      const emen = {
        0: {
          type: "",
          text: "已支付",
        },
        1: {
          type: "warning",
          text: "未支付",
        },
        2: {
          type: "danger",
          text: "支付失败",
        },
        3: {
          type: "success",
          text: "已完成",
        },
        4: {
          type: "",
          text: "待服务",
        },
        5: {
          type: "danger",
          text: "订单以取消",
        },
      };

      return emen[paymentStatus];
    },

    bandupdatepaymentStatus(scope) {
      this.fromVisible = !this.fromVisible;
      this.form.id = scope.row.id;
      this.form.radio = scope.row.paymentStatus.toString();
      this.form.index = scope.$index;
    },
    async updatepaymentStatus() {
      if (this.form.radio != this.tabledata[this.form.index].paymentStatus) {
        const isAlert = await this.$confirm(
          `您确定要修改序号为 ${this.form.index} 的订单状态吗？`,
          {
            type: "warning",
          }
        );
        if (isAlert !== "confirm") {
          return;
        }
        try {
          const res = await this.$request.put("/order/update", {
            id: this.form.id,
            paymentStatus: this.form.radio,
          });
          if (res.code == 200) {
            this.tabledata[this.form.index].paymentStatus = this.form.radio;
            this.$message.success("修改成功");
          }
        } catch (error) {
          console.log(error);
          this.$message.error("修改失败");
        } finally {
          this.butloading = !this.butloading;
        }
      } else {
        this.$message.info("当前状态与修改前相同");
      }
    },
    updateItem(scope) {
      const row = {
        index: scope.$index,
        id: scope.row.id,
        jiner: scope.row.jiner,
        ...scope.row.json,
      };
      for (const key in row) {
        this.form2[key] = row[key];
      }
      console.log(row);

      this.fromVisible2 = !this.fromVisible2;
    },

    awitAletr(options) {
      return new Promise((res) => {
        this.$alert(options.title, {
          callback: (action) => {
            res(action);
          },
        });
      });
    },

    async updateItemSubmit() {
      this.$refs.formRef2.validate(async (valid) => {
        this.butloading2 = true;
        if (valid) {
          const isAlert = await this.$confirm("您确定要修改吗？", {
            type: "warning",
          }).catch(() => {
            return Promise.resolve("cancel");
          });
          if (isAlert !== "confirm") {
            this.butloading2 = false;
            return;
          }

          const jsonData = JSON.parse(JSON.stringify(this.form2));
          delete jsonData.index;
          delete jsonData.jiner;
          delete jsonData.id;

          const res = await this.$request({
            url: "/order/update",
            method: "PUT",
            data: {
              id: this.form2.id,
              phone: this.form2.phone,
              dizhi: this.form2.dizhi,
              leavingAMessage: this.form2.leavingAMessage,
              fuwudate: dayjs(this.form2.fuwudate).format("YYYY-MM-DD HH:mm"),
              json: JSON.stringify(jsonData),
              jiner: this.form2.jiner,
            },
          }).catch(() => {
            this.$message.error("提交失败");
            this.butloading2 = false;
            return;
          });

          if (res.code == 200) {
            this.$message.success("提交成功");
            this.init();
          }
        } else {
          this.butloading2 = false;
          return false;
        }
      });
    },

    async deleteItem({ row }) {
      const isAlert = await this.$confirm("您确定要删除吗？", {
        type: "warning",
      });
      if (isAlert !== "confirm") {
        return;
      }
      try {
        await this.$request.put("/order/update", { id: row.id, isdel: 1 });
        this.$message.success("删除成功");
        this.init();
      } catch (error) {
        console.log(error);
        this.$message.error("删除失败");
      }
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-table__body-wrapper .cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

::v-deep .el-table__body-wrapper .cell:hover {
  overflow: visible;
  white-space: normal;
}
</style>
